<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="6">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>
          <div class="text-center">
            <!--            <el-avatar :size="100" :src="userInfo.faceUrl" />-->
            <el-upload
              class="avatar-uploader"
              action="#"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :limit="1"
            >
              <img v-if="userInfo.faceUrl" :src="userInfo.faceUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
          <ul class="list-group list-group-striped">
            <li>登录名：{{ userInfo.username }}</li>
            <li>真实姓名：{{ userInfo.realName }}</li>
            <li>用户昵称：{{ userInfo.nickname }}</li>
            <li>用户性别：{{ userInfo.gender }}</li>
            <li>手机号码：{{ userInfo.phone }}</li>
            <li>用户邮箱：{{ userInfo.email }}</li>
            <li>所属部门：{{ userInfo.deptName }}</li>
            <li>所属岗位：{{ userInfo.postName }}</li>
            <li>创建日期：{{ userInfo.createTime }}</li>
          </ul>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑区域 -->
      <el-col :span="18">
        <el-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="basic">
              <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="登录名称" prop="username">
                  <el-input v-model="form.username" readonly="true" disabled="true" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="form.realName" />
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                  <el-input v-model="form.nickname" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="form.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="form.gender">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSubmit">保存</el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
              <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="80px">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                    v-model="pwdForm.oldPassword"
                    type="password"
                    placeholder="请输入旧密码"
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="pwdForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="pwdForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUpdatePwd">保存</el-button>
                  <el-button @click="resetPwdForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<!-- 在 script 部分添加以下代码 -->
<script setup>
import { ref, toRefs, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.ts'
import router from '@/router/index.ts'
import { TOKEN_KEY } from '@/enums/CacheEnum.ts'

// ============================================================================================
const userInfo = ref({
  nickname: '',
  realName: '',
  username: '',
  isAdmin: false,
  gender: '',
  phone: '',
  email: '',
  deptName: '',
  postName: '',
  createTime: '',
  faceUrl: ''
})

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request({
      url: '/api/yyplatform/admin/layout/profile/info',
      method: 'get'
    })
    userInfo.value = res
    form.value = {
      nickname: res.nickname,
      realName: res.realName,
      username: res.username,
      gender: res.gender,
      phone: res.phone,
      email: res.email
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  }
}

// ============================================================================================

function beforeUpload(file) {
  const formData = new FormData()
  formData.append('file', file)
  request({
    url: `/api/yyplatform/admin/layout/profile/updateFaceUrl`,
    // '/api/yyplatform/admin/sys/file/uploadFile',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    console.log(res, '上传成功')
    // handleQuery()
    getUserInfo()
  })
  return false
}
// ============================================================================================

const form = ref({
  nickname: '',
  realName: '',
  username: '',
  isAdmin: false,
  gender: '',
  phone: '',
  email: '',
  deptName: '',
  postName: '',
  createTime: '',
  avatar: ''
})

const rules = {
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const formRef = ref()

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request({
          url: '/api/yyplatform/admin/layout/profile/updateInfo',
          method: 'post',
          data: form.value
        })
        ElMessage.success('修改成功')
        getUserInfo()
      } catch (error) {
        console.error('更新用户信息失败', error)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}

// ============================================================================================
const activeTab = ref('basic')
const pwdFormRef = ref()
const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const pwdRules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交修改密码表单
const handleUpdatePwd = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request({
          url: '/api/yyplatform/admin/layout/profile/updatePwd',
          method: 'post',
          data: {
            oldPassword: pwdForm.value.oldPassword,
            newPassword: pwdForm.value.newPassword
          }
        })
        ElMessage.success('密码修改成功')

        //logout()
        localStorage.setItem(TOKEN_KEY, '')
        localStorage.removeItem(TOKEN_KEY)
        await router.push('/login')
      } catch (error) {
        console.error('修改密码失败', error)
      }
    }
  })
}

// 重置密码表单
const resetPwdForm = () => {
  pwdFormRef.value.resetFields()
}

// ============================================================================================

onMounted(() => {
  getUserInfo()
})
// ============================================================================================
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  font-weight: bold;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.text-center {
  text-align: center;
  margin-bottom: 20px;
}

.list-group {
  list-style: none;
  padding: 0;
  margin: 0;

  li {
    padding: 10px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    font-size: var(--el-font-size-base);
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
